package drive.RemakeService.ServiceFormat;




import com.google.gson.Gson;
import drive.Mapper.*;
import drive.Model.*;
import drive.RemakeService.ServiceInterface.AdminManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminManagementServiceA implements AdminManagementService {

    @Value("${official.account.id}")
    private int OFFICIAL_ACCOUNT_ID; // 官方账号ID，从配置文件中获取

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    ChatSessionMapper chatSessionMapper;

    @Autowired
    ChatMessageMapper chatMessageMapper;

    @Autowired
    ReportRecordMapper reportRecordMapper;

    @Autowired
    TransactionOrderMapper transactionOrderMapper;

    @Autowired
    SecondHandItemMapper secondHandItemMapper;

    @Autowired
    UserMapper userMapper;
    Gson gson = new Gson();

    /**
     * 获取未审核的文章
     * @return 包含未审核文章列表的JSON字符串
     */
    @Override
    public String getPendingReviewArticles() {
        List<Article> articles = articleMapper.getPendingReviewArticles();
        return gson.toJson(articles);
    }

    /**
     * 更改文章为发布状态
     * @param articleId 文章ID
     * @return 操作结果的JSON字符串
     */
    @Transactional
    @Override
    public String publishArticle(int articleId) {
        Article article = articleMapper.findById(articleId);
        if (article == null) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"文章不存在\"}");
        }

        if (article.getStatus() == Article.Status.published) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"文章已处于发布状态\"}");
        }

        article.setStatus(Article.Status.published);
        articleMapper.update(article);
        sendOfficialMessage(article.getAuthorID(),"文章审核已通过");
        return gson.toJson("{\"status\":\"success\",\"message\":\"文章发布成功\"}");
    }

    @Transactional
    @Override
    public String redraftArticle(int articleId) {
        Article article = articleMapper.findById(articleId);
        if (article == null) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"文章不存在\"}");
        }

        if (article.getStatus() == Article.Status.draft) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"文章已处于草稿状态\"}");
        }

        article.setStatus(Article.Status.draft);
        articleMapper.update(article);
        sendOfficialMessage(article.getAuthorID(),"文章已打回");
        return gson.toJson("{\"status\":\"success\",\"message\":\"文章打回成功\"}");
    }

    /**
     * 获取所有未处理的举报
     * @return 包含未处理举报列表的JSON字符串
     */
    @Override
    public String getPendingReports() {
        List<ReportRecord> reports = reportRecordMapper.getPendingReports();
        return gson.toJson(reports);
    }

    /**
     * 修改举报为已处理并提交处理结果
     * @param reportId 举报ID
     * @param handlingResult 处理结果
     * @return 操作结果的JSON字符串
     */
    @Transactional
    @Override
    public String handleReport(int reportId, String handlingResult) {
        ReportRecord reportRecord = reportRecordMapper.findByReportID(reportId);
        if (reportRecord == null) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"举报记录不存在\"}");
        }

        if (reportRecord.getReportStatus() == ReportRecord.Status.handled) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"该举报已处理\"}");
        }

        reportRecord.setReportStatus(ReportRecord.Status.handled);
        reportRecord.setHandlingResult(handlingResult);
        reportRecord.setHandlingTime(new Date());
        reportRecordMapper.update(reportRecord);
        sendOfficialMessage(reportRecord.getReporterID(),handlingResult);

        return gson.toJson("{\"status\":\"success\",\"message\":\"举报处理成功\"}");
    }

    /**
     * 获取文章总量
     * @return 包含文章总量的JSON字符串
     */
    @Override
    public String getArticleCount() {
        long count = articleMapper.countArticles();
        return gson.toJson("{\"articleCount\":" + count + "}");
    }

    /**
     * 按月获取文章总量
     * @return 包含每月文章总量的JSON字符串
     */
    @Override
    public String getArticleCountMonthly() {
        List<Map<String, Object>> result = articleMapper.getArticleCountMonthly();
        return gson.toJson(result);
    }

    private void sendOfficialMessage(int authorId, String messageContent) {
        ChatSession chatSession = chatSessionMapper.findByUserIDs(OFFICIAL_ACCOUNT_ID,authorId);
        if (chatSession == null) {
            // 创建会话
            chatSession = new ChatSession();
            chatSession.setUser1ID(OFFICIAL_ACCOUNT_ID);
            chatSession.setUser2ID(authorId);
            chatSession.setCreationTime(new Date());
            chatSessionMapper.add(chatSession);
            System.out.println(chatSession);
        }
        System.out.println("发送关注消息中");
        // 发送消息
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setChatSessionID(chatSession.getChatSessionID());
        chatMessage.setSenderID(OFFICIAL_ACCOUNT_ID);
        chatMessage.setContent(messageContent);
        chatMessage.setSendTime(new Date());
        chatMessage.setStatus(ChatMessage.Status.sending);
        chatMessageMapper.add(chatMessage);

        chatSessionMapper.update_time(chatSession.getChatSessionID());
    }

    /**
     * 获取交易总量（订单数和金额）
     * @return 包含交易总量信息的JSON字符串
     */
    @Override
    public String getTotalTransactions() {
        List<TransactionOrder> orders = transactionOrderMapper.findAll();
        long orderCount = orders.size();
        BigDecimal totalAmount = new BigDecimal("0.00");

        for (TransactionOrder order : orders) {
            Secondhanditem item = secondHandItemMapper.findByItemID(order.getItemID());
            if (item != null) {
                totalAmount = totalAmount.add(item.getPrice());
            }
        }

        return gson.toJson("{"
                + "\"orderCount\":" + orderCount + ","
                + "\"totalAmount\":" + totalAmount.toString()
                + "}");
    }
    /**
     * 按月统计交易总量（订单数和金额）
     * @return 包含每月交易总量信息的JSON字符串
     */
    @Override
    public String getTotalTransactionsMonthly() {
        List<TransactionOrder> orders = transactionOrderMapper.findAll();
        Map<String, Map<String, Object>> monthlyStats = new HashMap<>();

        for (TransactionOrder order : orders) {
            Secondhanditem item = secondHandItemMapper.findByItemID(order.getItemID());
            if (item == null) {
                continue;
            }

            String month = order.getCreationTime().toString().substring(0, 7); // 提取年月部分

            if (!monthlyStats.containsKey(month)) {
                monthlyStats.put(month, new HashMap<>());
                monthlyStats.get(month).put("orderCount", 0);
                monthlyStats.get(month).put("totalAmount", new BigDecimal("0.00"));
            }

            int orderCount = (int) monthlyStats.get(month).get("orderCount");
            BigDecimal totalAmount = (BigDecimal) monthlyStats.get(month).get("totalAmount");

            monthlyStats.get(month).put("orderCount", orderCount + 1);
            monthlyStats.get(month).put("totalAmount", totalAmount.add(item.getPrice()));
        }

        return gson.toJson(monthlyStats.values());
    }

    /**
     * 按月统计所有用户的订单总金额和订单数量
     * @return 包含每月统计信息的JSON字符串
     */
    @Override
    public String getMonthlyTransactionStats() {
        List<TransactionOrder> orders = transactionOrderMapper.findAll();
        Map<String, Map<String, Object>> monthlyStats = new HashMap<>();

        for (TransactionOrder order : orders) {
            Secondhanditem item = secondHandItemMapper.findByItemID(order.getItemID());
            if (item == null) {
                continue;
            }

            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
            String month = sdf1.format(order.getCreationTime());

            if (!monthlyStats.containsKey(month)) {
                monthlyStats.put(month, new HashMap<>());
                monthlyStats.get(month).put("month", month);
                monthlyStats.get(month).put("orderCount", 0);
                monthlyStats.get(month).put("totalAmount", new BigDecimal("0.00"));
            }

            int orderCount = (int) monthlyStats.get(month).get("orderCount");
            BigDecimal totalAmount = (BigDecimal) monthlyStats.get(month).get("totalAmount");

            monthlyStats.get(month).put("orderCount", orderCount + 1);
            monthlyStats.get(month).put("totalAmount", totalAmount.add(item.getPrice()));
        }
        System.out.println(monthlyStats);

        return gson.toJson(monthlyStats.values());
    }

    @Override
    public String ban_user(int userID){
        userMapper.ban_user(userID);
        return "封禁成功";
    }

    /**
     * 分页获取用户列表
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 包含用户列表和分页信息的JSON字符串
     */
    @Override
    public String getUserList(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<User> users = userMapper.getUsers(offset, pageSize);
        int total = userMapper.getUserCount();

        return gson.toJson("{"
                + "\"status\":\"success\","
                + "\"data\":" + gson.toJson(users) + ","
                + "\"total\":" + total + ","
                + "\"pageNum\":" + pageNum + ","
                + "\"pageSize\":" + pageSize
                + "}");
    }
}